package com.nxcy.com.nxcy.servlet;


import com.google.gson.Gson;
import com.mongodb.client.*;
import org.bson.Document;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;

@WebServlet(urlPatterns = {"/student/list.do"})
public class StudentListServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String url = "mongodb://g08:abc%408@mongo.zhledu.cn:27017/g08";
        MongoClient client = MongoClients.create(url);
        MongoIterable<String> names = client.listDatabaseNames();
        MongoDatabase g08 = client.getDatabase("g08");
        MongoCollection<Document> collection = g08.getCollection("student");

        Document query = new Document();
        String sno = request.getParameter("sno");
        if (sno != null && sno != "") {
            query.append("sno", Pattern.compile(sno));
        }
        String name = request.getParameter("name");
        if (name != null && name != "") {
            query.append("name", Pattern.compile(name));
        }
        String sex = request.getParameter("sex");
        if (sex != null && sex != "") {
            query.append("sex", sex);
        }
        String idCard = request.getParameter("idCard");
        if (idCard != null && idCard != "") {
            query.append("idCard", Pattern.compile(idCard));
        }
        String major = request.getParameter("major");
        if (major != null && major != "") {
            query.append("major", major);
        }

        long count = collection.countDocuments(query);

        int pageNum = Integer.parseInt(request.getParameter("pageNum"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        final FindIterable<Document> list = collection.find(query).skip((pageNum - 1) * pageSize).limit(pageSize);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        List<Document> students = new ArrayList<>();
        for (Document d : list) {
            students.add(d);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("count", count);
        map.put("list", students);
        Gson gson = new Gson();
        response.getWriter().write(gson.toJson(map));
    }
}
